package HashTable;

import java.util.*;

public class _692_TopKFrequentWords {
    public List<String> topKFrequent(String[] words, int k) {
        Map<String, Integer> counts = new HashMap<>();
        for (String word : words) {
            counts.put(word, counts.getOrDefault(word, 0) + 1);
        }
        List<String> res = new ArrayList<>(counts.keySet());
        Collections.sort(res, (w1, w2) -> counts.get(w1) == counts.get(w2) ? w1.compareTo(w2) : counts.get(w2) - counts.get(w1));
        return res.subList(0,k);
    }
}
